<script setup lang="ts" name="SystemUser">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import useCopy from '@/hooks/web/useCopy'
import { getIntDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
import { UserApi, UserType } from '@/api/system/user/index'
import { checkPermit, computedOperateWidth } from '@/utils/permit'
import { CommonStatusEnum } from '@/enums/commonEnums'
import { dateFormatter } from '@/utils/dateUtil'
import { dataToFile } from '@/components/Excel/src/helper'
import { randomPassword } from '@/utils/random'
import DepartTree from './DepartTree.vue'
import UserImportForm from './UserImportForm.vue'
import UserAssignRoleForm from './UserAssignRoleForm.vue'
import UserForm from './UserForm.vue'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const { copy } = useCopy()
const { clipboardRef, copiedRef } = copy()

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const queryLoading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数
const isExpanded = ref(false) // 查询条件折叠展开
const queryParams = ref({
  pageIndex: 1,
  pageSize: 20,
  nickname: undefined,
  mobile: undefined,
  status: undefined,
  departId: undefined,
  create_time: []
})

const expandChange = () => {
  isExpanded.value = !isExpanded.value
}

const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  queryLoading.value = true
  try {
    const data = await UserApi.page(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    queryLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageIndex = 1
  getList()
}

const departTreeRef = ref()
/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageIndex: 1,
    pageSize: 20,
    nickname: undefined,
    mobile: undefined,
    status: undefined,
    departId: undefined,
    create_time: []
  }
  queryFormRef.value?.resetFields()
  departTreeRef.value!.removeChecked()
  handleQuery()
}

/** 处理部门被点击 */
const handleDepartNodeClick = async (row) => {
  queryParams.value.departId = row.id
  await getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 修改用户状态 */
const handleStatusChange = async (row: UserType) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? t('status', 'enable') : t('status', 'unEnable')
    await message.confirm(t('sys.user', 'confirmUserStatus', [text, row.username]))
    // 发起修改状态
    await UserApi.updateStatus(row.id!, row.status)
    message.success(t('message', 'updateSuccess'))
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 导出按钮操作 */
const ExcelExportDialogRef = ref()

const filedList = ref([
  { key: 'id', value: 'ID' },
  { key: 'username', value: t('sys.user', 'username') },
  { key: 'nickname', value: t('sys.user', 'nickname') },
  { key: 'departName', value: t('sys.user', 'depart') },
  { key: 'mobile', value: t('sys.user', 'mobile') },
  { key: 'email', value: t('sys.user', 'email') },
  { key: 'sex', value: t('sys.user', 'sex') },
  { key: 'create_time', value: t('common', 'createTime') },
  { key: 'status', value: t('common', 'status') },
  { key: 'remark', value: t('common', 'remark') }
])
/** 导出按钮操作 */
const handleExport = async () => {
  ExcelExportDialogRef.value.open()
}

const exportDone = async (res) => {
  if (res.dataScope === 1) {
    dataToFile(list.value, res)
  } else if (res.dataScope === 3) {
    const allList = await UserApi.export()
    dataToFile(allList, res)
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: UserType) => {
  switch (command) {
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleRole':
      handleRole(row)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.delete(id)
    message.success(t('message.del', 'success'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 重置密码 */
const handleResetPwd = async (row: UserType) => {
  try {
    // 重置的二次确认
    const result = await message.prompt(
      t('sys.user', 'newPwd', [row.username]),
      t('message', 'reminder'),
      {
        inputPlaceholder: t('sys.user.rules', 'emptyPwd'),
        inputType: 'text',
        inputValue: randomPassword(),
        inputValidator: value => {
          const reg = /^[a-zA-Z0-9_\-\.]{6,20}$/
          if (!value) {
            return t('sys.user.rules', 'emptyPwd')
          } else if (!reg.test(value)) {
            return t('sys.user.rules', 'errPwd')
          } else {
            return true
          }
        }
      }
    )
    const password = result.value
    clipboardRef.value = password
    // 发起重置
    await UserApi.resetPwd(row.id!, password)
    if (unref(copiedRef)) {
      message.success(t('sys.user', 'successCopy', [password]))
    } else {
      message.success(t('sys.user', 'success', [password]))
    }
  } catch { }
}

/** 分配角色 */
const assignRoleFormRef = ref()
const handleRole = (row: UserType) => {
  assignRoleFormRef.value.open(row)
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>

<template>
  <PageCard direction="row">
    <DepartTree ref="departTreeRef" @node-click="handleDepartNodeClick" />
    <ContentFormTable border>
      <template #header>
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item :label="t('sys.user', 'nickname')" prop="nickname">
            <el-input v-model="queryParams.nickname" :placeholder="t('sys.user.rules', 'nickname')" clearable class="!w-160px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item v-if="isExpanded" :label="t('sys.user', 'mobile')" prop="mobile">
            <el-input v-model="queryParams.mobile" :placeholder="t('sys.user.rules', 'mobile')" clearable class="!w-160px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item v-if="isExpanded" :label="t('common', 'status')" prop="status">
            <el-select v-model="queryParams.status" :placeholder="t('sys.user.rules', 'status')" clearable class="!w-160px">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <ElFormItem v-if="isExpanded" :label="t('common', 'createTime')" prop="create_time">
            <el-date-picker
              v-model="queryParams.create_time"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              clearable
              :start-placeholder="t('common', 'startDate')"
              :end-placeholder="t('common', 'endDate')"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleQuery" />
          </ElFormItem>
          <el-form-item>
            <el-button type="primary" :disabled="queryLoading" icon="Search" @click="handleQuery">{{ t('action',
              'search') }}</el-button>
            <el-button icon="Refresh" :disabled="queryLoading" @click="resetQuery">{{ t('action', 'reset')
            }}</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-if="checkPermit(['system:user:create'])" type="success" icon="Plus" @click="openForm('create')">{{ t('action', 'create') }}</el-button>
            <CButton v-if="checkPermit(['system:user:import'])" type="danger" :disabled="queryLoading" :onClick="handleImport" preIcon="ri:import-line" :title="t('action', 'import')" />
            <CButton v-if="checkPermit(['system:user:export'])" type="warning" :disabled="queryLoading" :onClick="handleExport" preIcon="ri:export-line" :title="t('action', 'export')" />
            <CButton text type="info" :disabled="queryLoading" :onClick="expandChange" :preIcon="isExpanded ? 'ep:arrow-up' : 'ep:arrow-down'" :title="isExpanded ? t('action', 'fold') : t('action', 'unfold')" />
          </el-form-item>
        </el-form>
      </template>
      <template #content>
        <el-table v-loading="queryLoading && systemConfig.loadingType === 'module'" :data="list" border>
          <el-table-column type="index" :label="t('common', 'index')" width="60" align="center" fixed="left" />
          <el-table-column prop="id" label="ID" width="70" fixed="left" align="center" />
          <el-table-column prop="username" :label="t('sys.user', 'username')" show-overflow-tooltip min-width="180" fixed="left" />
          <el-table-column prop="nickname" :label="t('sys.user', 'nickname')" show-overflow-tooltip min-width="180" />
          <el-table-column prop="departName" :label="t('sys.depart', 'title')" show-overflow-tooltip min-width="180" align="center" />
          <el-table-column prop="mobile" :label="t('sys.user', 'mobile')" width="120" align="center" />
          <el-table-column prop="email" :label="t('sys.user', 'email')" show-overflow-tooltip min-width="180" align="center" />
          <el-table-column prop="create_time" :label="t('common', 'createTime')" align="center" :formatter="dateFormatter" width="180" />
          <el-table-column prop="remark" :label="t('common', 'remark')" show-overflow-tooltip min-width="180" align="center" />
          <el-table-column prop="status" :label="t('common', 'status')" width="90" align="center" fixed="right">
            <template #default="scope">
              <template v-if="checkPermit(['system:user:update-status'])">
                <el-switch v-model="scope.row.status" :active-value="CommonStatusEnum.ENABLE" :inactive-value="CommonStatusEnum.DISABLE" @change="handleStatusChange(scope.row)" />
              </template>
              <template v-else>
                <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
              </template>
            </template>
          </el-table-column>
          <el-table-column
            v-if="checkPermit(['system:user:update', 'system:user:delete', 'system:user:update-password', 'system:permission:assign-user-role'])"
            prop="operate"
            :label="t('common', 'operate')"
            :width="computedOperateWidth(['system:menu:update', 'system:menu:delete', [ 'system:user:update-password', 'system:permission:assign-user-role' ]])"
            fixed="right">
            <template #default="scope">
              <el-button v-if="checkPermit(['system:user:update'])" type="primary" icon="Edit" @click="openForm('update', scope.row.id)" />
              <el-button v-if="checkPermit(['system:user:delete'])" type="danger" icon="Delete" @click="handleDelete(scope.row.id)" />
              <el-dropdown
                v-if="checkPermit([
                'system:user:update-password',
                'system:permission:assign-user-role'
              ])"
                @command="(command) => handleCommand(command, scope.row)">
                <el-button type="warning" icon="More" class="ml-12px" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-if="checkPermit(['system:user:update-password'])" command="handleResetPwd"> <SvgIcon icon="ep:key" />{{ t('sys.user', 'resetPassword') }} </el-dropdown-item>
                    <el-dropdown-item v-if="checkPermit(['system:permission:assign-user-role'])" command="handleRole"> <SvgIcon icon="ep:circle-check" />{{ t('sys.user', 'assignRole') }} </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageIndex" :total="total" :disabled="queryLoading" @pagination="getList" />
        <!-- 添加或修改用户对话框 -->
        <UserForm ref="formRef" @success="getList" />
        <!-- 用户导入对话框 -->
        <UserImportForm ref="importFormRef" @success="getList" />
        <!-- 分配角色 -->
        <UserAssignRoleForm ref="assignRoleFormRef" @success="getList" />
        <!-- 用户导出对话框 -->
        <ExcelExportDialog ref="ExcelExportDialogRef" :filename="t('sys.user', 'title')" :hasSelected="false" :fieldList="filedList" @success="exportDone" />
      </template>
    </ContentFormTable>
  </PageCard>
</template>

<style scoped lang="scss">
.el-table {
  width: 100%;
  height: 100%;
}
</style>
